package com.kt.emall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.kt.common.constant.AuthServerConstant;
import com.kt.common.utils.HttpUtils;
import com.kt.common.utils.R;
import com.kt.emall.auth.feign.MemberFeignService;
import com.kt.common.vo.MemberRespVO;
import com.kt.emall.auth.vo.SocialUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: e-mall
 * @description: 处理社交登录请求
 * @author: KamTang
 * @create: 2022-01-14 09:14
 **/
@Slf4j
@Controller
public class OAuth2Controller {

    @Autowired
    MemberFeignService memberFeignService;

    /**
     * 社交登录成功回调
     * @param code
     * @return
     * @throws Exception
     */
    @GetMapping("/oauth2.0/weibo/success")
    public String weibo(@RequestParam("code") String code, HttpSession session) throws Exception {
        Map<String, String> header = new HashMap<>();
        Map<String, String> query = new HashMap<>();

        // 根据code获取access_token
        Map<String, String> map = new HashMap<>();
        map.put("client_id", "3711425321");
        map.put("client_secret", "d4ebbfa752cf467170a75333006abcdc");
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code", code);
        HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", header, query, map);

        // 处理
        if (response.getStatusLine().getStatusCode() == 200) {
            // 获取到了access_token
            String json = EntityUtils.toString(response.getEntity());
            SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

            // 当前用户如果是第一次进入网站，自动为其注册（为当前用户生成一个会员信息账号，以后这个社交账号就对应指定的会员）
            // login or register
            R oauth2Login = memberFeignService.oauth2Login(socialUser);
            if (oauth2Login.getCode() == 0) {
                MemberRespVO memberRespVO = oauth2Login.getData("data", new TypeReference<MemberRespVO>() {
                });
                log.info("登录成功：用户信息 => {}", memberRespVO.toString());
                // 指定域名为父域名，实现子父域名的session公用  -> springSession
                // 由于memberRespVO是对象，所以需要序列化。
                // TODO 使用JSON方式的序列化将对象序列化到redis中
                // TODO session默认的作用域为当前域（解决子域session共享问题）
                session.setAttribute(AuthServerConstant.LOGIN_USER, memberRespVO);
                // 登录成功就返回首页
                return "redirect:http://gulimall.com";
            } else {
                return "redirect:http://auth.gulimall.com/login.html";
            }
        } else {
            return "redirect:http://auth.gulimall.com/login.html";
        }


    }
}
